import { FormInstance } from 'vant'

import { ref, unref, nextTick, watch } from 'vue'

import { cloneDeep } from 'lodash-es'

export const useFormMethods = (props: Record<string, any>) => {
  const formData = ref<Record<string, any>>({})
  const formInstance = ref<FormInstance>()
  const initialization = (instance: FormInstance) => {
    formInstance.value = instance
  }

  const getFormInstance = async () => {
    const instance = unref(formInstance.value)
    await nextTick()
    return instance
  }

  const validate = async () => {
    const instance = await getFormInstance()
    return new Promise((resovle, reject) => {
      instance
        ?.validate()
        .then(() => {
          resovle(instance?.getValues())
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  const getFormValue = async () => {
    const instance = await getFormInstance()
    return instance?.getValues()
  }

  const resetValidation = async () => {
    const instance = await getFormInstance()
    instance?.resetValidation()
  }

  const scrollToField = async (name: string, alignToTop: boolean) => {
    const instance = await getFormInstance()
    instance?.scrollToField(name, alignToTop)
  }

  watch(
    () => props.value,
    (val) => {
      formData.value = cloneDeep(val)
    },
    {
      deep: true,
      immediate: true
    }
  )

  return {
    initialization,
    validate,
    resetValidation,
    scrollToField,
    getFormValue,
    formData
  }
}
